import * as Cesium from 'cesium';

export class MapTools {
  constructor(cesiumManager) {
    this.cesiumManager = cesiumManager;
    this.drawHandler = null;
  }

  // 放大
  zoomIn() {
    this.cesiumManager.viewer.camera.zoomIn(2.0);
  }

  // 缩小
  zoomOut() {
    this.cesiumManager.viewer.camera.zoomOut(2.0);
  }

  // 全图
  fullExtent() {
    this.cesiumManager.viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(112.98, 28.19, 3000000),
      duration: 1.0
    });
  }

  // 平移模式
  panMode() {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;
    
    const viewer = this.cesiumManager.viewer;
    
    // 取消当前绘制操作
    if (this.drawHandler) {
      this.drawHandler.destroy();
      this.drawHandler = null;
    }
    
    // 启用默认的相机控制
    viewer.scene.screenSpaceCameraController.enableRotate = true;
    viewer.scene.screenSpaceCameraController.enableTranslate = true;
    viewer.scene.screenSpaceCameraController.enableZoom = true;
    viewer.scene.screenSpaceCameraController.enableTilt = true;
    viewer.scene.screenSpaceCameraController.enableLook = true;
  }

  // 选择模式
  selectMode() {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;
    
    const viewer = this.cesiumManager.viewer;
    
    // 取消当前绘制操作
    if (this.drawHandler) {
      this.drawHandler.destroy();
      this.drawHandler = null;
    }
    
    // 创建选择处理器
    const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    
    handler.setInputAction((click) => {
      const pickedObject = viewer.scene.pick(click.position);
      if (pickedObject && pickedObject.id) {
        console.log('选中的实体:', pickedObject.id);
        // 可以在这里添加选中效果
        if (pickedObject.id.polyline) {
          // 选中线要素
          pickedObject.id.polyline.width = 5;
          pickedObject.id.polyline.material = Cesium.Color.YELLOW;
        } else if (pickedObject.id.polygon) {
          // 选中面要素
          pickedObject.id.polygon.material = Cesium.Color.YELLOW.withAlpha(0.8);
        } else if (pickedObject.id.point) {
          // 选中点要素
          pickedObject.id.point.pixelSize = 15;
          pickedObject.id.point.color = Cesium.Color.YELLOW;
        }
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    
    // 5秒后自动解除选择模式
    setTimeout(() => {
      handler.destroy();
    }, 5000);
  }

  // 加载CZML时间动态场景
  loadCzml(url) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;
    
    const viewer = this.cesiumManager.viewer;
    return Cesium.CzmlDataSource.load(url).then(dataSource => {
      viewer.dataSources.add(dataSource);
      return dataSource;
    });
  }

  // 加载WGS84高精度地形数据
  loadTerrain(terrainProviderUrl) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;
    
    const viewer = this.cesiumManager.viewer;
    const terrainProvider = new Cesium.CesiumTerrainProvider({
      url: terrainProviderUrl
    });
    viewer.terrainProvider = terrainProvider;
  }

  // 加载KML文件
  loadKml(url) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;
    
    const viewer = this.cesiumManager.viewer;
    return Cesium.KmlDataSource.load(url).then(dataSource => {
      viewer.dataSources.add(dataSource);
      return dataSource;
    });
  }

  // 加载GeoJSON文件
  loadGeoJson(url) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;
    
    const viewer = this.cesiumManager.viewer;
    return Cesium.GeoJsonDataSource.load(url).then(dataSource => {
      viewer.dataSources.add(dataSource);
      return dataSource;
    });
  }

  // 加载glTF模型
  loadGltfModel(url, position, options = {}) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;
    
    const viewer = this.cesiumManager.viewer;
    
    // 将经纬度转换为笛卡尔坐标
    const cartesianPosition = Cesium.Cartesian3.fromDegrees(
      position.longitude, 
      position.latitude, 
      position.height || 0
    );
    
    // 默认配置
    const defaultOptions = {
      uri: url,
      modelMatrix: Cesium.Transforms.eastNorthUpToFixedFrame(cartesianPosition),
      scale: options.scale || 1.0,
      minimumPixelSize: options.minimumPixelSize || 128,
      maximumScale: options.maximumScale || 20000
    };
    
    // 合并用户选项
    const modelOptions = Object.assign({}, defaultOptions, options);
    
    const model = viewer.scene.primitives.add(Cesium.Model.fromGltf(modelOptions));
    
    // 添加模型点击事件处理
    model.readyPromise.then(function(model) {
      // 模型加载完成后的回调
      const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
      handler.setInputAction(function(click) {
        const picked = viewer.scene.pick(click.position);
        if (Cesium.defined(picked) && picked.node && picked.mesh) {
          // 获取模型节点信息
          console.log('选中的模型节点:', picked.node);
          console.log('选中的模型网格:', picked.mesh);
          
          // 如果模型有属性数据，则输出属性信息
          // if (picked primitive === model) {
          //   console.log('点击了模型:', model);
          //   // 可以在这里处理模型数据获取逻辑
            if (options.onModelClick) {
              options.onModelClick(picked, model);
            }
          // }
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }).otherwise(function(error) {
      console.error('模型加载失败:', error);
    });
    
    return model;
  }

  // 加载3D Tiles
  load3DTiles(url) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;
    
    const viewer = this.cesiumManager.viewer;
    const tileset = new Cesium.Cesium3DTileset({
      url: url
    });
    
    viewer.scene.primitives.add(tileset);
    return tileset;
  }

  // 添加摄像头控制功能
  enableCameraControl() {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;
    
    const viewer = this.cesiumManager.viewer;
    
    // 启用相机控制器的所有功能
    const controller = viewer.scene.screenSpaceCameraController;
    controller.enableRotate = true;
    controller.enableTranslate = true;
    controller.enableZoom = true;
    controller.enableTilt = true;
    controller.enableLook = true;
    
    console.log('摄像头控制已启用');
  }

  // 添加飞行路径规划功能
  createFlightPath(positions, options = {}) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;
    
    const viewer = this.cesiumManager.viewer;
    
    // 默认选项
    const defaultOptions = {
      duration: 10, // 飞行持续时间（秒）
      loop: false,  // 是否循环
      orientation: {  // 相机方向设置
        heading: 0,
        pitch: -Math.PI / 4,
        roll: 0
      }
    };
    
    const flightOptions = Object.assign({}, defaultOptions, options);
    
    // 创建飞行路径
    const property = new Cesium.SampledPositionProperty();
    const startTime = viewer.clock.currentTime;
    
    positions.forEach((position, index) => {
      const time = Cesium.JulianDate.addSeconds(startTime, index * (flightOptions.duration / positions.length), new Cesium.JulianDate());
      const positionCartesian = Cesium.Cartesian3.fromDegrees(position.longitude, position.latitude, position.height || 1000);
      property.addSample(time, positionCartesian);
    });
    
    // 创建飞行实体
    const flightEntity = viewer.entities.add({
      // 修复availability属性的使用
      availability: new Cesium.TimeIntervalCollection([
        new Cesium.TimeInterval({
          start: startTime,
          stop: Cesium.JulianDate.addSeconds(startTime, flightOptions.duration, new Cesium.JulianDate())
        })
      ]),
      position: property,
      orientation: new Cesium.VelocityOrientationProperty(property),
      model: {
        uri: '/models/Cesium_Air.glb', // 使用默认飞机模型
        minimumPixelSize: 64
      },
      path: {
        show: true,
        leadTime: 0,
        trailTime: flightOptions.duration,
        width: 3,
        material: new Cesium.PolylineGlowMaterialProperty({
          glowPower: 0.1,
          color: Cesium.Color.YELLOW
        }),
        resolution: 1
      }
    });
    
    // 设置相机跟随
    viewer.trackedEntity = flightEntity;
    
    // 飞行完成后停止跟踪
    viewer.clock.onTick.addEventListener(() => {
      if (Cesium.JulianDate.greaterThan(viewer.clock.currentTime, 
          Cesium.JulianDate.addSeconds(startTime, flightOptions.duration, new Cesium.JulianDate()))) {
        viewer.trackedEntity = undefined;
      }
    });
    
    // 开始飞行
    viewer.clock.multiplier = 1;
    
    return flightEntity;
  }

  // 城市漫游功能
  startCityRoaming(cityPositions, options = {}) {
    // let cityPositions = []
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;
    
    const viewer = this.cesiumManager.viewer;
    
    // 默认选项
    const defaultOptions = {
      duration: 20, // 漫游总时间（秒）
      stopsDuration: 3, // 每个站点停留时间（秒）
      loop: true
    };
    
    const roamingOptions = Object.assign({}, defaultOptions, options);
    
    // 生成以长沙市为中心的随机漫游点（10公里范围内）
    const positions = [];
    const names = [];
    const centerLon = 112.982279; // 长沙市经度
    const centerLat = 28.194090;  // 长沙市纬度
    const maxDistanceKm = 10;     // 10公里范围
    
    // 添加起始点（长沙市中心）
    positions.push({
      longitude: centerLon,
      latitude: centerLat,
      height: 1000
    });
    names.push("长沙市");
    
    // 生成周边随机点
    for (let i = 0; i < 8; i++) {
      // 随机角度和距离
      const angle = Math.random() * Math.PI * 2;
      const distance = Math.random() * maxDistanceKm;
      
      // 将距离转换为经纬度偏移（近似计算）
      const deltaLon = (distance * Math.cos(angle)) / (111.32 * Math.cos(centerLat * Math.PI/180));
      const deltaLat = (distance * Math.sin(angle)) / 110.574;
      
      positions.push({
        longitude: centerLon + deltaLon,
        latitude: centerLat + deltaLat,
        height: 500 + Math.random() * 1500 // 高度在500-2000米之间
      });
      
      // 生成模拟名称
      const locationTypes = ['公园', '商场', '学校', '医院', '广场', '车站', '景区', '大厦'];
      const adjectives = ['中心', '新区', '老街', '湖畔', '山脚', '河边'];
      const locationType = locationTypes[Math.floor(Math.random() * locationTypes.length)];
      const adjective = adjectives[Math.floor(Math.random() * adjectives.length)];
      names.push(`长沙${adjective}${locationType}${i+1}`);
    }
    
    // 创建时间间隔
    const startTime = viewer.clock.currentTime;
    const stopTime = Cesium.JulianDate.addSeconds(startTime, roamingOptions.duration, new Cesium.JulianDate());
    
    // 添加站点标记
    const siteEntities = [];
    positions.forEach((position, index) => {
      const entity = viewer.entities.add({
        position: Cesium.Cartesian3.fromDegrees(position.longitude, position.latitude, position.height),
        point: {
          pixelSize: 8,
          color: Cesium.Color.BLUE
        },
        label: {
          text: names[index],
          font: "12px sans-serif",
          fillColor: Cesium.Color.YELLOW,
          outlineColor: Cesium.Color.BLACK,
          outlineWidth: 2,
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          pixelOffset: new Cesium.Cartesian2(0, -15)
        }
      });
      siteEntities.push(entity);
    });
    
    // 相机漫游控制
    let currentIndex = 0;
    let isMoving = false;
    let infoEntity = null; // 用于显示当前位置信息的实体
    
    // 相机移动到指定位置的函数
    const moveToPosition = (index) => {
      if (index >= positions.length) return;
      
      const position = positions[index];
      const cartesianPosition = Cesium.Cartesian3.fromDegrees(
        position.longitude,
        position.latitude,
        position.height
      );
      
      // 禁用用户相机控制
      viewer.scene.screenSpaceCameraController.enableTranslate = false;
      viewer.scene.screenSpaceCameraController.enableZoom = false;
      viewer.scene.screenSpaceCameraController.enableRotate = false;
      viewer.scene.screenSpaceCameraController.enableTilt = false;
      
      isMoving = true;
      
      // 相机飞向目标位置，调整视角使目标位置居中
      viewer.camera.flyTo({
        destination: cartesianPosition,
        orientation: {
          heading: Cesium.Math.toRadians(0.0),
          pitch: Cesium.Math.toRadians(-15.0),
          roll: 0.0
        },
        duration: 2.0,
        complete: () => {
          isMoving = false;
          
          // 在当前位置添加信息展示点
          if (infoEntity) {
            viewer.entities.remove(infoEntity);
          }
          
          infoEntity = viewer.entities.add({
            position: cartesianPosition,
            point: {
              pixelSize: 12,
              color: Cesium.Color.RED,
              outlineColor: Cesium.Color.WHITE,
              outlineWidth: 2
            },
            label: {
              text: `当前位置: ${names[index]}`,
              font: "14px sans-serif",
              fillColor: Cesium.Color.WHITE,
              outlineColor: Cesium.Color.BLACK,
              outlineWidth: 2,
              style: Cesium.LabelStyle.FILL_AND_OUTLINE,
              verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
              pixelOffset: new Cesium.Cartesian2(0, -20)
            }
          });
          
          // 暂停一段时间以展示当前位置
          setTimeout(() => {
            if (roamingOptions.loop && currentIndex === positions.length - 1) {
              // 循环回到起点
              currentIndex = 0;
              moveToPosition(currentIndex);
            } else if (!roamingOptions.loop && currentIndex === positions.length - 1) {
              // 恢复用户相机控制
              viewer.scene.screenSpaceCameraController.enableTranslate = true;
              viewer.scene.screenSpaceCameraController.enableZoom = true;
              viewer.scene.screenSpaceCameraController.enableRotate = true;
              viewer.scene.screenSpaceCameraController.enableTilt = true;
              
              // 清理信息展示点
              if (infoEntity) {
                viewer.entities.remove(infoEntity);
              }
            } else {
              currentIndex++;
              moveToPosition(currentIndex);
            }
          }, 3000); // 停留3秒
        }
      });
    };
    
    // 启动漫游
    moveToPosition(currentIndex);
    
    // 漫游控制
    if (roamingOptions.loop) {
      viewer.clock.onTick.addEventListener(() => {
        if (Cesium.JulianDate.greaterThanOrEquals(viewer.clock.currentTime, stopTime)) {
          // 重置时间以实现循环
          viewer.clock.currentTime = startTime;
        }
      });
    }
    
    // 设置时钟
    viewer.clock.multiplier = 1;
    // 确保时钟在有效范围内
    viewer.clock.startTime = startTime;
    viewer.clock.stopTime = stopTime;
    viewer.clock.currentTime = startTime;
    
    // 确保实体在添加后立即可见
    viewer.scene.requestRender();
    
    return siteEntities;
  }

  // 停止所有摄像头动画
  stopCameraAnimation() {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;
    
    const viewer = this.cesiumManager.viewer;
    viewer.trackedEntity = undefined;
    viewer.clock.multiplier = 1;
    
    console.log('摄像头动画已停止');
  }

  // 湖南省轮廓高亮显示 其他不显示隐藏
  highlightChangshaBoundary() {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;
    
    const viewer = this.cesiumManager.viewer;
    
    // 长沙市近似边界坐标（实际项目中应从数据源获取精确边界数据）
    // 这里使用一个近似的多边形表示长沙市边界
    const changshaBoundary = [
      111.8, 27.8,  // 西南角
      111.8, 28.5,  // 西北角
      113.2, 28.5,  // 东北角
      113.2, 27.8,  // 东南角
      111.8, 27.8   // 回到起点，闭合多边形
    ];
    
    // 创建长沙市边界实体
    const boundaryEntity = viewer.entities.add({
      name: 'Changsha Boundary',
      polygon: {
        hierarchy: Cesium.Cartesian3.fromDegreesArray(changshaBoundary),
        material: Cesium.Color.YELLOW.withAlpha(0.3),
        outline: true,
        outlineColor: Cesium.Color.YELLOW,
        outlineWidth: 2
      }
    });
    
    // 创建一个覆盖整个地球的遮罩，但长沙市区域镂空
    // 首先定义一个大的矩形区域（代表整个地球的一部分）
    const earthExtent = [
      -180, -90,
      -180, 90,
      180, 90,
      180, -90,
      -180, -90
    ];
    
    // 创建遮罩实体，使用拉伸多边形来创建"反向"遮罩效果
    const maskEntity = viewer.entities.add({
      name: 'Mask',
      polygon: {
        hierarchy: {
          // 外部边界是整个视图区域
          positions: Cesium.Cartesian3.fromDegreesArray(earthExtent),
          // 内部挖空长沙市区域
          holes: [{
            positions: Cesium.Cartesian3.fromDegreesArray(changshaBoundary)
          }]
        },
        material: Cesium.Color.BLACK.withAlpha(0.7),
        height: 0
      }
    });
    
    // 调整相机视角到长沙市
    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(112.98, 28.19, 200000),
      duration: 2.0
    });
    
    return {
      boundary: boundaryEntity,
      mask: maskEntity
    };
  }

  // 创建围绕长沙市的流动发光轨迹线条
  createChangshaGlowingTrail() {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;
    
    const viewer = this.cesiumManager.viewer;
    
    // 长沙市边界坐标（用于创建围绕城市的轨迹）
    const changshaTrail = [
      111.8, 27.8,  // 西南角
      111.8, 28.5,  // 西北角
      113.2, 28.5,  // 东北角
      113.2, 27.8,  // 东南角
      111.8, 27.8   // 回到起点，闭合多边形
    ];
    
    // 创建流动发光轨迹线条
    const trailEntity = viewer.entities.add({
      name: 'Changsha Glowing Trail',
      polyline: {
        positions: Cesium.Cartesian3.fromDegreesArray(changshaTrail),
        width: 5,
        material: new Cesium.PolylineGlowMaterialProperty({
          color: Cesium.Color.CYAN,
          glowPower: 0.25,
          taperPower: 1.0
        }),
        depthFailMaterial: new Cesium.PolylineGlowMaterialProperty({
          color: Cesium.Color.CYAN,
          glowPower: 0.25,
          taperPower: 1.0
        })
      }
    });
    
    // 创建动态流动效果
    const flowingTrailEntity = viewer.entities.add({
      name: 'Flowing Trail',
      polyline: {
        positions: Cesium.Cartesian3.fromDegreesArray(changshaTrail),
        width: 8,
        material: new Cesium.PolylineFlowMaterialProperty({
          color: Cesium.Color.BLUE,
          duration: 3000,
          repeat: new Cesium.Cartesian2(30, 30)
        })
      }
    });
    
    // 调整相机视角到长沙市
    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(112.98, 28.19, 200000),
      duration: 2.0
    });
    
    return {
      trail: trailEntity,
      flowingTrail: flowingTrailEntity
    };
  }

  // 创建粒子系统
  createParticleSystem(options = {}) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;

    const viewer = this.cesiumManager.viewer;

    // 默认配置
    const defaultOptions = {
      image: undefined,
      startPosition: new Cesium.Cartesian3(0, 0, 0),
      startVelocity: new Cesium.Cartesian3(0, 0, 1),
      emissionRate: 50,
      lifetime: 5.0,
      scale: 1.0,
      color: Cesium.Color.WHITE,
      startScale: 1.0,
      endScale: 0.0,
      particleSize: 5.0,
      mass: 1.0,
      emitter: new Cesium.PointEmitter(),
      bursts: [],
      modelMatrix: Cesium.Matrix4.IDENTITY
    };

    // 合并配置
    const particleOptions = Object.assign({}, defaultOptions, options);

    // 创建粒子系统
    const particleSystem = viewer.scene.primitives.add(new Cesium.ParticleSystem({
      image: particleOptions.image || this.getDefaultParticleImage(),
      startPosition: particleOptions.startPosition,
      startVelocity: particleOptions.startVelocity,
      emissionRate: particleOptions.emissionRate,
      emitter: particleOptions.emitter,
      bursts: particleOptions.bursts,
      lifetime: particleOptions.lifetime,
      startColor: particleOptions.color,
      endColor: particleOptions.color.withAlpha(0.0),
      startScale: particleOptions.startScale,
      endScale: particleOptions.endScale,
      sizeInMeters: particleOptions.particleSize,
      mass: particleOptions.mass,
      updateCallback: particleOptions.updateCallback,
      modelMatrix: particleOptions.modelMatrix
    }));

    return particleSystem;
  }

  // 获取默认粒子图像
  getDefaultParticleImage() {
    // 创建一个简单的圆形粒子图像
    const canvas = document.createElement('canvas');
    canvas.width = 32;
    canvas.height = 32;
    const context = canvas.getContext('2d');
    
    context.beginPath();
    context.arc(16, 16, 16, 0, Cesium.Math.TWO_PI, true);
    context.closePath();
    context.fillStyle = 'rgb(255, 255, 255)';
    context.fill();
    
    return canvas.toDataURL();
  }

  // 创建烟花效果粒子系统
  createFireworkEffect(position) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;

    const viewer = this.cesiumManager.viewer;
    const cartesianPosition = Cesium.Cartesian3.fromDegrees(position.longitude, position.latitude, position.height || 100);

    // 创建多个粒子系统模拟烟花效果
    const particleSystems = [];
    
    // 爆炸效果
    const explosionSystem = this.createParticleSystem({
      startPosition: cartesianPosition,
      startVelocity: new Cesium.Cartesian3(0, 0, 0),
      emissionRate: 0, // 瞬间发射
      bursts: [
        new Cesium.ParticleBurst({
          time: 0.0,
          minimum: 100,
          maximum: 200
        })
      ],
      lifetime: 2.0,
      startScale: 1.0,
      endScale: 0.0,
      color: Cesium.Color.fromRandom({alpha: 1.0}),
      particleSize: 15.0,
      emitter: new Cesium.SphereEmitter(0.1),
      updateCallback: (particle) => {
        // 添加重力效果
        particle.velocity.z -= 9.8 * particle.mass * 0.01;
      }
    });
    
    particleSystems.push(explosionSystem);
    
    return particleSystems;
  }

  // 创建雨雪效果粒子系统
  createWeatherEffect(type = 'rain', options = {}) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;

    const viewer = this.cesiumManager.viewer;
    
    // 默认配置
    const defaultWeatherOptions = {
      particleCount: 1000,
      speed: type === 'rain' ? 50 : 10,
      size: type === 'rain' ? 2 : 5,
      color: type === 'rain' ? Cesium.Color.BLUE : Cesium.Color.WHITE
    };
    
    const weatherOptions = Object.assign({}, defaultWeatherOptions, options);
    
    // 创建盒子发射器，覆盖整个视图区域
    const emitterRegion = new Cesium.BoxEmitter(new Cesium.Cartesian3(1000000.0, 1000000.0, 100000.0));
    
    // 创建天气粒子系统
    const weatherSystem = this.createParticleSystem({
      emissionRate: weatherOptions.particleCount / 10,
      startVelocity: new Cesium.Cartesian3(0, 0, -weatherOptions.speed),
      lifetime: 10.0,
      startScale: 1.0,
      endScale: 1.0,
      color: weatherOptions.color,
      particleSize: weatherOptions.size,
      emitter: emitterRegion,
      updateCallback: (particle) => {
        // 循环粒子位置
        if (particle.position.z < -100000.0) {
          particle.position = new Cesium.Cartesian3(
            particle.position.x,
            particle.position.y,
            100000.0
          );
        }
      }
    });
    
    return weatherSystem;
  }

  // 创建烟雾效果粒子系统
  createSmokeEffect(position, options = {}) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;

    const viewer = this.cesiumManager.viewer;
    const cartesianPosition = Cesium.Cartesian3.fromDegrees(position.longitude, position.latitude, position.height || 0);

    // 默认配置
    const defaultSmokeOptions = {
      color: Cesium.Color.GRAY.withAlpha(0.5),
      particleSize: 30,
      emissionRate: 20,
      lifetime: 10.0
    };
    
    const smokeOptions = Object.assign({}, defaultSmokeOptions, options);
    
    // 创建烟雾粒子系统
    const smokeSystem = this.createParticleSystem({
      startPosition: cartesianPosition,
      startVelocity: new Cesium.Cartesian3(2, 0, 5),
      emissionRate: smokeOptions.emissionRate,
      lifetime: smokeOptions.lifetime,
      startScale: 1.0,
      endScale: 5.0,
      color: smokeOptions.color,
      particleSize: smokeOptions.particleSize,
      emitter: new Cesium.ConeEmitter(Cesium.Math.toRadians(30)),
      updateCallback: (particle) => {
        // 添加风力和扩散效果
        particle.velocity.x += 0.1;
        particle.velocity.z += 0.05;
      }
    });
    
    return smokeSystem;
  }

  // 移除粒子系统
  removeParticleSystem(particleSystem) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;
    
    const viewer = this.cesiumManager.viewer;
    viewer.scene.primitives.remove(particleSystem);
  }

  // 移除高亮显示
  removeHighlight() {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;
    
    const viewer = this.cesiumManager.viewer;
    
    // 移除所有高亮相关的实体
    const entitiesToRemove = [];
    viewer.entities.values.forEach(entity => {
      if (entity.name === 'Changsha Boundary' || entity.name === 'Mask' || 
          entity.name === 'Changsha Glowing Trail' || entity.name === 'Flowing Trail') {
        entitiesToRemove.push(entity);
      }
    });
    
    entitiesToRemove.forEach(entity => {
      viewer.entities.remove(entity);
    });
  }

  // 加载国产底图服务（高德、腾讯、百度、天地图）
  loadDomesticMapService(serviceType, options = {}) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;
    
    const viewer = this.cesiumManager.viewer;
    
    // 移除现有的影像图层
    viewer.imageryLayers.removeAll();
    
    // 定义不同服务商的URL模板和参数
    const mapServices = {
      gaode: {
        url: 'https://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
        options: {
          layer: 'gaode',
          style: 'default',
          format: 'image/png',
          tileMatrixSetID: 'GoogleMapsCompatible'
        }
      },
      tencent: {
        url: 'https://p0.map.gtimg.com/sateTiles/{z}/{sx}/{sy}/{x}_{y}.jpg',
        options: {
          layer: 'tencent',
          style: 'default',
          format: 'image/jpeg',
          tileMatrixSetID: 'GoogleMapsCompatible'
        }
      },
      baidu: {
        url: 'http://online{s}.map.bdimg.com/tile/?qt=tile&x={x}&y={y}&z={z}&styles=pl',
        options: {
          layer: 'baidu',
          style: 'default',
          format: 'image/png',
          tileMatrixSetID: 'GoogleMapsCompatible',
          subdomains: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
        }
      },
      tianditu: {
        url: 'http://t{s}.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}',
        options: {
          layer: 'tianditu',
          style: 'default',
          format: 'image/png',
          tileMatrixSetID: 'GoogleMapsCompatible',
          subdomains: ['0', '1', '2', '3', '4', '5', '6', '7']
        }
      }
    };
    
    // 检查请求的服务类型是否支持
    if (!mapServices[serviceType]) {
      console.error(`不支持的地图服务类型: ${serviceType}`);
      console.info('支持的服务类型包括: gaode, tencent, baidu, tianditu');
      return;
    }
    
    // 获取选定服务的配置
    const serviceConfig = mapServices[serviceType];
    
    // 合并选项
    const imageryOptions = Object.assign({}, serviceConfig.options, options);
    
    // 创建并添加影像图层
    const imageryProvider = new Cesium.UrlTemplateImageryProvider({
      url: serviceConfig.url,
      subdomains: imageryOptions.subdomains || ['1', '2', '3', '4'],
      minimumLevel: 1,
      maximumLevel: 18,
      ...imageryOptions
    });
    
    const layer = viewer.imageryLayers.addImageryProvider(imageryProvider);
    
    console.log(`${serviceType}地图服务加载成功`);
    return layer;
  }
}